package com.je.paas.document.controller;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.je.core.base.JERequestWrapper;
import com.je.core.constants.push.PushType;
import com.je.core.exception.PlatformExceptionEnum;
import com.je.core.result.BaseRespResult;
import com.je.core.util.SecurityUserHolder;
import com.je.core.util.StringUtil;
import com.je.message.service.DwrManager;
import com.je.message.service.UserMsgManaer;
import com.je.paas.disk.exception.DiskException;
import com.je.paas.disk.exception.DiskExceptionEnum;
import com.je.paas.disk.model.*;
import com.je.paas.disk.model.bo.DiskBO;
import com.je.paas.disk.model.bo.Owner;
import com.je.paas.disk.service.DiskNodeService;
import com.je.paas.document.exception.DocumentException;
import com.je.paas.document.exception.DocumentExceptionEnum;
import com.je.paas.document.model.MetadataEnum;
import com.je.paas.document.model.bean.FileUpload;
import com.je.paas.document.model.bo.FileBO;
import com.je.paas.document.service.DocumentService;
import com.je.paas.document.util.MetadataUtil;
import com.je.paas.document.vo.*;
import com.je.rbac.model.EndUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * 网盘
 *
 * @author wangmm@ketr.com.cn
 * @date 2019/8/27
 */
@Controller("diskController")
@RequestMapping(value = "/je/disk")
public class DiskController {

    @Autowired
    private DiskNodeService diskNodeService;
    @Autowired
    private DocumentController documentController;
    @Autowired
    private UserMsgManaer userMsgManaer;
    @Autowired
    private DwrManager dwrManager;
    @Autowired
    private DocumentService documentService;

    /**
     * 网盘上传
     *
     * @param request  请求对象
     * @param nodeId   上传目录ID[为空则使用根目录]
     * @param diskType 网盘类型[self,company],DiskTypeEnum
     * @return DiskFileVO 上传的文件信息
     */
    @RequestMapping(value = "/file", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult file(HttpServletRequest request, Long nodeId, String diskType) throws DiskException {
        //校验请求是否是附件类型
        if (!(request instanceof MultipartHttpServletRequest)) {
            return BaseRespResult.errorResult(PlatformExceptionEnum.JE_DOC_FILE_READ_ERROR.getCode(), "未找到附件");
        }
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        //默认文件上传字段名
        String funcUploadField = "files";
        //获取文件
        List<MultipartFile> files = multipartRequest.getFiles(funcUploadField);
        //校验是否存在文件
        if (files == null || files.isEmpty()) {
            throw new DiskException("未找到附件", DiskExceptionEnum.DISK_UPLOAD_PARAM_ERROR);
        }

        //网盘类型枚举
        DiskTypeEnum diskTypeEnum = DiskTypeEnum.getDefault(diskType);
        if (diskTypeEnum == null) {
            throw new DiskException("网盘类型错误", DiskExceptionEnum.DISK_UPLOAD_PARAM_ERROR);
        }

        //归属人信息
        Owner owner = buildOwner(diskType);

        //业务元数据
        JSONObject metadata = new JSONObject();
        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);


        //验证权限
        HashMap<String, String> userInfoMap = new HashMap<>();
        if (DiskTypeEnum.COMPANY.getCode().equals(diskType)) {
            //获取当前登陆人信息
            EndUser currentUser = SecurityUserHolder.getCurrentUser();

            userInfoMap.put("roleId", currentUser.getRoleIds());
            userInfoMap.put("roleCode", currentUser.getRoleCodes());
            userInfoMap.put("company", currentUser.getJtgsId());
            userInfoMap.put("dept", currentUser.getDeptId());
            userInfoMap.put("userId", currentUser.getUserId());
            userInfoMap.put("userName", currentUser.getUsername());
            if (!diskNodeService.isDocAdmin(currentUser.getUserId()) && !currentUser.getSaasAdmin()) {
                String nodeIds = "null";
                if (nodeId != null) {
                    nodeIds = nodeId.toString();
                }
                diskNodeService.checkCompanyPower(userInfoMap, owner, nodeIds, null, OperationTypeEnum.UPLOAD.getCode());
            }
        }

        // TODO 新增上传记录
        List<DiskBO> transfer = diskNodeService.addUploadRecordToTransfer(files, metadata);

        //调用业务方法
        try {
            //保存附件
            List<FileUpload> fileUploadFiles = Lists.newArrayList();
            for (MultipartFile file : files) {
                FileUpload fileUpload = new FileUpload(file.getOriginalFilename(),
                        file.getContentType(), file.getSize(), file.getInputStream());
                fileUploadFiles.add(fileUpload);
            }
            //保存文件并持久化业务数据
            List<DiskBO> diskBOS = diskNodeService.uploadFile(fileUploadFiles, nodeId, diskTypeEnum, owner, metadata);
            List<DiskFileVO> diskFileVOS = transformVOList(diskBOS);

            // TODO 修改上传记录为成功
            diskNodeService.modifyUploadRecordToTransfer(diskBOS, transfer, TransferStatusEnum.SUCCESS.getCode());

            //如果是公司文件夹，重新设置权限
            if (diskType.equals(DiskTypeEnum.COMPANY.getCode())) {
                diskNodeService.empowerAgain(diskBOS.get(0).getParent().toString(), diskFileVOS.get(0).getNodeId().toString(), OperationTypeEnum.UPLOAD.getCode(), metadata);
                for (DiskFileVO diskFileVO : diskFileVOS) {
                    diskFileVO.setRoleRoleCode(RoleTypeEnum.EDIT.getCode());
                    diskFileVO.setSetRoleType("staff");
                }
            }
            return BaseRespResult.successResult(diskFileVOS);
        } catch (DocumentException e) {
            e.printStackTrace();
            return BaseRespResult.errorResult(e.getErrorCode(), e.getCode(), e.getErrorMsg());
        } catch (Exception e) {

            // TODO 修改上传记录为失败
            diskNodeService.modifyUploadRecordToTransfer(null, transfer, TransferStatusEnum.FAILURE.getCode());

            if (e instanceof DiskException) {
                return BaseRespResult.errorResult("", "", e.getMessage());
            }
            throw new DiskException("文件上传失败", DiskExceptionEnum.DISK_UPLOAD_ERROR, e);
        }
    }

    /**
     * 网盘上传通过 fileKey
     *
     * @param request  请求对象
     *  fileKeys  上传文件的fileKeys
     *  nodeId   上传目录ID[为空则使用根目录]
     *  diskType 网盘类型[self,company],DiskTypeEnum 默认为self
     *  DiskFileVO 上传的文件信息
     */
    @RequestMapping(value = "/uploadByFileKey", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult uploadByFileKey(HttpServletRequest request) {
        //获取fileKey
        String fileKeys = request.getParameter("fileKeys");
        if(StringUtils.isEmpty(fileKeys)){
            return BaseRespResult.errorResult("", DiskExceptionEnum.DISK_UNKNOWN_FILE.getCode(), "fileKey为空");
        }
        //获取 FileBO
        List<FileBO> FileBOs = new ArrayList<>();
        String[] fileKeyStrings=fileKeys.split(",");
        for (String fileKey : fileKeyStrings) {
            FileBO fileBO=documentService.readFile(fileKey);
            if(fileBO == null ){
                return BaseRespResult.errorResult("", DiskExceptionEnum.DISK_UNKNOWN_FILE.getCode(), "根据fileKey没有获得相关的文件信息");
            }
            FileBOs.add(fileBO);
        }
        //网盘类型枚举
        String diskType = request.getParameter("diskType");
        if( StringUtils.isEmpty(diskType) ){
            diskType = "self";
        }
        DiskTypeEnum diskTypeEnum = DiskTypeEnum.getDefault(diskType);
        //获取nodeID
        //Long nodeId = request.getParameter("nodeId") == null?null:Long.parseLong(request.getParameter("nodeId"));
        //获取nodeID
        Long nodeId = "".equals(request.getParameter("nodeId"))? null : Long.parseLong(request.getParameter("nodeId"));
        //归属人信息
        Owner owner = buildOwner(diskType);
        //业务元数据
        JSONObject metadata = new  JSONObject();
        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);
        //验证权限
        if (DiskTypeEnum.COMPANY.getCode().equals(diskType)) {
            //获取当前登陆人信息
            EndUser currentUser = SecurityUserHolder.getCurrentUser();
            HashMap<String, String> userInfoMap = new HashMap<>();
            userInfoMap.put("roleId", currentUser.getRoleIds());
            userInfoMap.put("roleCode", currentUser.getRoleCodes());
            userInfoMap.put("company", currentUser.getJtgsId());
            userInfoMap.put("dept", currentUser.getDeptId());
            userInfoMap.put("userId", currentUser.getUserId());
            userInfoMap.put("userName", currentUser.getUsername());
            if (!diskNodeService.isDocAdmin(currentUser.getUserId()) && !currentUser.getSaasAdmin()) {
                String nodeIds = "null";
                if (nodeId != null) {
                    nodeIds = nodeId.toString();
                }
                diskNodeService.checkCompanyPower(userInfoMap, owner, nodeIds, null, OperationTypeEnum.UPLOAD.getCode());
            }
        }

        // TODO 新增上传记录
        List<DiskBO> transfer = diskNodeService.addUploadFileBosRecordToTransfer(FileBOs, metadata);

        //调用业务方法
        try {
            //保存附件
            List<FileUpload> fileUploadFiles = Lists.newArrayList();
            for (FileBO fileBO:FileBOs) {
                FileUpload fileUpload = new FileUpload(fileBO.getRelName(), fileBO.getContentType(), fileBO.getSize(), fileBO.getFile());
                fileUploadFiles.add(fileUpload);
            }
            //保存文件并持久化业务数据
            List<DiskBO> diskBOS = diskNodeService.uploadFile(fileUploadFiles, nodeId, diskTypeEnum, owner, metadata);
            List<DiskFileVO> diskFileVOS = transformVOList(diskBOS);

            // TODO 修改上传记录为成功
            diskNodeService.modifyUploadRecordToTransfer(diskBOS, transfer, TransferStatusEnum.SUCCESS.getCode());

            //如果是公司文件夹，重新设置权限
            if (diskType.equals(DiskTypeEnum.COMPANY.getCode())) {
                diskNodeService.empowerAgain(diskBOS.get(0).getParent().toString(), diskFileVOS.get(0).getNodeId().toString(), OperationTypeEnum.UPLOAD.getCode(), metadata);
                for (DiskFileVO diskFileVO : diskFileVOS) {
                    diskFileVO.setRoleRoleCode(RoleTypeEnum.EDIT.getCode());
                    diskFileVO.setSetRoleType("staff");
                }
            }

            return BaseRespResult.successResult(diskFileVOS);
        } catch (Exception e) {

            // TODO 修改上传记录为失败
            diskNodeService.modifyUploadRecordToTransfer(null, transfer, TransferStatusEnum.FAILURE.getCode());

            if (e instanceof DiskException) {
                return BaseRespResult.errorResult("", "", e.getMessage());
            }
            throw new DiskException("文件上传失败", DiskExceptionEnum.DISK_UPLOAD_ERROR, e);
        }
    }

    /**
     * 创建文件夹目录结构
     *
     * @param structure
     * @param nodeId
     * @param diskType
     * @return
     */
    @RequestMapping(value = "/takeStructure", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult takeStructure(String structure, Long nodeId, String diskType) {

        if (!StringUtils.isNotEmpty(structure)) {
            return BaseRespResult.errorResult("", "", "参数异常");
        }

        //网盘类型枚举
        DiskTypeEnum diskTypeEnum = DiskTypeEnum.getDefault(diskType);
        if (diskTypeEnum == null) {
            return BaseRespResult.errorResult("", DiskExceptionEnum.DISK_UPLOAD_PARAM_ERROR.getCode(), "网盘类型错误");
        }

        //归属人信息
        Owner owner = buildOwner(diskType);

        //业务元数据
        JSONObject metadata = new JSONObject();
        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);

        try {
            JSONObject obj = diskNodeService.createFolderStructure(structure, nodeId, diskTypeEnum, owner, metadata);
            return BaseRespResult.successResult(obj, "目录结构创建成功");
        } catch (DiskException e) {
            return BaseRespResult.errorResult("", "", e.getMessage());
        } catch (Exception e) {
            return BaseRespResult.errorResult("", "", "结构创建失败");
        }
    }


    /**
     * 下载[包含打包下载]
     *
     * @param response 响应对象
     * @param nodeIds  目录/文件ID集合
     * @param fileName 打包文件名称
     */
    @ResponseBody
    @RequestMapping(value = "/download")
    public BaseRespResult download(HttpServletResponse response, String nodeIds, String fileName, String diskType) {
        if (Strings.isNullOrEmpty(nodeIds)) {
            throw new DocumentException("请指定目录或文件！", DocumentExceptionEnum.DOCUMENT_ERROR);
        }
        InputStream downloadInputStream = null;

        //业务元数据
        JSONObject metadata = new JSONObject();
        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);

        List<DiskBO> diskBOList = new ArrayList<>();

        OutputStream toClient = null;

        try {
            //添加下载记录
            if (DiskTypeEnum.COMPANY.getCode().equals(diskType)) {
                diskNodeService.insertFileLog(nodeIds, OperationTypeEnum.DOWNLOAD.getCode(), metadata);
            }

            Map<String, InputStream> files = diskNodeService.downloadNode(nodeIds);
            Set<String> keys = files.keySet();
            for (String eachKey : keys) {
                if (Strings.isNullOrEmpty(fileName)) {
                    fileName = eachKey;
                }
                downloadInputStream = files.get(eachKey);
                break;
            }

            //验证权限
            if (DiskTypeEnum.COMPANY.getCode().equals(diskType)) {
                //获取当前登陆人信息
                EndUser currentUser = SecurityUserHolder.getCurrentUser();
                HashMap<String, String> userInfoMap = new HashMap<>();
                userInfoMap.put("roleId", currentUser.getRoleIds());
                userInfoMap.put("roleCode", currentUser.getRoleCodes());
                userInfoMap.put("company", currentUser.getJtgsId());
                userInfoMap.put("dept", currentUser.getDeptId());
                userInfoMap.put("userId", currentUser.getUserId());
                userInfoMap.put("userName", currentUser.getUsername());
                //归属人信息
                Owner owner = buildOwner(diskType);
                if (!diskNodeService.isDocAdmin(currentUser.getUserId()) && !currentUser.getSaasAdmin()) {
                    diskNodeService.checkCompanyPower(userInfoMap, owner, nodeIds, null, OperationTypeEnum.DOWNLOAD.getCode());
                }
            }

            //TODO 传输开始记录
            String transferFileName = fileName;
            diskBOList = diskNodeService.addDownloadRecordToTransfer(nodeIds, metadata, transferFileName);

            fileName = URLEncoder.encode(StringUtils.isNotBlank(fileName) ? fileName : System.currentTimeMillis() + ".zip", "UTF-8");

            if (downloadInputStream == null) {
                throw new DocumentException("没有找到文件！", DocumentExceptionEnum.DOCUMENT_ERROR);
            }
            response.reset();
            response.setHeader("Content-Type", "application/octet-stream;charset=\"utf-8\"");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.setCharacterEncoding("utf-8");
            //写入文件流
//            response.setContentType(ContentTypeSuffixEnum.S_zip.getContentType());
            toClient = response.getOutputStream();
            IoUtil.copy(downloadInputStream, toClient);
            IoUtil.close(downloadInputStream);

            //TODO 传输完成记录
            diskNodeService.modifyDownloadRecordToTransfer(diskBOList, TransferStatusEnum.SUCCESS.getCode());
            return BaseRespResult.successResult("", "下载成功");

        } catch (IOException e) {

            //TODO 传输下载失败记录
            diskNodeService.modifyDownloadRecordToTransfer(diskBOList, TransferStatusEnum.FAILURE.getCode());

            return BaseRespResult.errorResult("", "", "打包下载失败");
        }
    }


    /**
     * 判断是不是空文件夹
     *
     * @param nodeIds
     */
    @ResponseBody
    @RequestMapping(value = "/checkDownload", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult checkDownload(String nodeIds) {

        //判断是不是空文件夹
        Boolean emptyFolder = diskNodeService.emptyFolder(nodeIds);
        if (!emptyFolder) {
            return BaseRespResult.errorResult("", "", "文件夹内容为空不支持下载");
        }

        return BaseRespResult.successResult("", "");
    }


    /**
     * 文本图片预览
     *
     * @param type
     * @param request
     * @param response
     * @param nodeId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/preview/{type}")
    public BaseRespResult preview(@PathVariable(name = "type") String type,
                                  JERequestWrapper request, HttpServletResponse response, Long nodeId, String diskType) {

        //验证参数
        if (StringUtils.isBlank(type) || nodeId == null) {
            return BaseRespResult.errorResult("", "", "参数异常！");
        }

        //业务元数据
        JSONObject metadata = new JSONObject();
        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);
        //归属人信息
        Owner owner = buildOwner(diskType);


        try {
            //查询出文件key;
            String fileKey = diskNodeService.queryFileInfo(nodeId, owner);

            //如果时文本
            if ("text".equals(type)) {
                documentController.previewAndDownload(request, response, fileKey, "");
            }

            //如果是图片
            if ("picture".equals(type)) {
                documentController.thumbnail(request, response, fileKey, "");
            }

        } catch (DiskException e) {
            return BaseRespResult.errorResult("", "", e.getMessage());
        }

        return BaseRespResult.successResult("成功！");
    }


    /**
     * 是否是文档管理员
     *
     * @return
     */
    @RequestMapping(value = "/isDocumentAdmin", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult isDocumentAdmin() {

        EndUser currentUser = SecurityUserHolder.getCurrentUser();
        String userId = currentUser.getUserId();
        Boolean isDocAdmin = diskNodeService.isDocAdmin(userId);
        //如果不是文档管理员，查看是不是系统管理员，如果是，返回true
        if (!isDocAdmin && !currentUser.getSaasAdmin()) {
            return BaseRespResult.errorResult("", "", "");
        }

        return BaseRespResult.successResult("", "");
    }


    /**
     * 文件列表接口[含搜索]
     *
     * @param diskType 网盘类型[self,company] 必填
     * @param parentId 父级目录ID，无值默认一级目录
     * @param tag      标签
     * @param suffix   文件类型
     * @param key      搜索关键字
     * @param order    排序条件
     * @return List<DiskFileVO> 目录/文件列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult<List<DiskFileVO>> list(String diskType, String nodeType, Long parentId, String tag, String suffix, String key, String order) {

        //判断错误数据
        if (!DiskTypeEnum.COMPANY.getCode().equals(diskType) && !DiskTypeEnum.SELF.getCode().equals(diskType)) {
            return BaseRespResult.errorResult("", "", "参数信息错误！");
        }

        //归属人信息
        Owner owner = buildOwner(diskType);
        if (DiskTypeEnum.COMPANY.getCode().equals(diskType)) {
            owner = new Owner(SecurityUserHolder.getCurrentUser().getZhId(), SecurityUserHolder.getCurrentUser().getZhMc());
        }
        if (StringUtils.isBlank(owner.getOwnerId())) {
            throw new DiskException(String.format("%s 查不到文件归属对象ID", diskType), DiskExceptionEnum.DISK_UPLOAD_PARAM_ERROR);
        }

        //业务元数据
        JSONObject metadata = new JSONObject();
        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);

        try {

            //如果是公司,验证权限,并返回对应权限的文件夹
            if (DiskTypeEnum.COMPANY.getCode().equals(diskType)) {

                //获取当前登陆人信息
                EndUser currentUser = SecurityUserHolder.getCurrentUser();
                HashMap<String, String> userInfoMap = new HashMap<>();
                userInfoMap.put("roleId", currentUser.getRoleIds());
                userInfoMap.put("roleCode", currentUser.getRoleCodes());
                userInfoMap.put("company", currentUser.getGsbmId());
                userInfoMap.put("dept", currentUser.getDeptId());
                userInfoMap.put("userId", currentUser.getUserId());
                userInfoMap.put("userName", currentUser.getUsername());
                userInfoMap.put("saasAdmin", currentUser.getSaasAdmin().toString());

                //根据权限辨析文件信息
                List<DiskBO> companyBoList = diskNodeService.companyList(userInfoMap, owner, nodeType, parentId, suffix, key, tag, order);
                List<DiskNodeRelViewVO> diskNodeList = new ArrayList<>();
                StringBuffer diskNodeIds = new StringBuffer();
                for (DiskBO bo : companyBoList) {
                    DiskNodeRelViewVO diskNodeVO = new DiskNodeRelViewVO();
                    BeanUtils.copyProperties(bo, diskNodeVO);
                    if(diskNodeIds.toString().indexOf(bo.getId().toString())>=0 && diskNodeIds.length()>0){
                        continue;
                    }
                    diskNodeList.add(diskNodeVO);
                    diskNodeIds.append(bo.getId()+",");
                }
                return BaseRespResult.successResult(diskNodeList);
            }

            //查看个人文件
            List<DiskBO> diskBOList = diskNodeService.nodeListInfo(metadata, diskType, nodeType, parentId, tag, suffix, key, order, owner);
            //BO转VO
            List<DiskFileVO> fileVOS = new ArrayList<>();
            for (DiskBO diskBO : diskBOList) {
                DiskFileVO fileVO = new DiskFileVO();
                BeanUtils.copyProperties(diskBO, fileVO);
                fileVOS.add(fileVO);
            }
            return BaseRespResult.successResult(fileVOS);
        } catch (DiskException e) {
            return BaseRespResult.errorResult("", "", e.getMessage());
        } catch (Exception e) {
            return BaseRespResult.errorResult("", "", "查询异常！");
        }
    }

    /**
     * 新建目录文件夹
     *
     * @param parentId   父级目录
     * @param folderName 名称
     * @return DiskFileVO 新建的文件夹信息
     */
    @RequestMapping(value = "/folder/create", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult<List<DiskFileVO>> folderCreate(Long parentId, String folderName, String diskType) {

        //业务元数据
        JSONObject metadata = new JSONObject();
        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);
        //文件归属对象

        //归属人信息
        Owner owner = buildOwner(diskType);
        if (DiskTypeEnum.COMPANY.equals(diskType)) {
            owner = new Owner(SecurityUserHolder.getCurrentUser().getZhId(), SecurityUserHolder.getCurrentUser().getZhMc());
        }
        if (StringUtils.isBlank(owner.getOwnerId())) {
            throw new DiskException(String.format("%s 查不到文件归属对象ID", diskType), DiskExceptionEnum.DISK_UPLOAD_PARAM_ERROR);
        }

        //校验文件夹名称是否为空
        if (!StringUtils.isNotEmpty(folderName)) {
            return BaseRespResult.errorResult("", "", "文件名不许为空！");
        }

        try {

            //如果是公司，进行权限验证
            if (DiskTypeEnum.COMPANY.getCode().equals(diskType)) {
                //获取当前登陆人信息
                EndUser currentUser = SecurityUserHolder.getCurrentUser();
                HashMap<String, String> userInfoMap = new HashMap<>();
                userInfoMap.put("roleId", currentUser.getRoleIds());
                userInfoMap.put("roleCode", currentUser.getRoleCodes());
                userInfoMap.put("company", currentUser.getJtgsId());
                userInfoMap.put("dept", currentUser.getDeptId());
                userInfoMap.put("userId", currentUser.getUserId());
                userInfoMap.put("userName", currentUser.getUsername());
                if (!diskNodeService.isDocAdmin(currentUser.getUserId()) && !currentUser.getSaasAdmin()) {
                    String nodeId = "null";
                    if (parentId != null) {
                        nodeId = parentId.toString();
                    }
                    diskNodeService.checkCompanyPower(userInfoMap, owner, nodeId, null, OperationTypeEnum.CREATE.getCode());
                }
            }

            //进行创建
            List<DiskBO> diskBOList = diskNodeService.folderCreate(parentId, folderName, diskType, owner, metadata);
            List<DiskFileVO> diskFileVOS = new ArrayList<>();
            for (DiskBO diskBO : diskBOList) {
                DiskFileVO diskFileVO = new DiskFileVO();
                BeanUtils.copyProperties(diskBO, diskFileVO);
                diskFileVOS.add(diskFileVO);
            }
            return BaseRespResult.successResult(diskFileVOS, "更新成功！");
        } catch (DiskException e) {
            return BaseRespResult.errorResult("", "", e.getMessage());
        } catch (Exception e) {
            return BaseRespResult.errorResult("", "", "更新异常！");
        }
    }

    /**
     * 目录列表接口[树形懒加载](无用)
     *
     * @param parentId 父级目录ID，无值默认一级目录
     * @param nodeName 目录名称
     * @param nodeTag  目录标签
     * @return List<DiskFileVO> 目录列表
     */
    @ResponseBody
    @RequestMapping(value = "/folder/list", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult<List<DiskFileVO>> folderList(Long parentId, String nodeName, String nodeTag) {
        return null;
    }

    /**
     * 目录搜索接口
     *
     * @param nodeName 目录名称
     * @param nodeTag  目录标签
     * @return List<DiskFileVO> 目录列表
     */
    @ResponseBody
    @RequestMapping(value = "/folder/query", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult<List<DiskFileVO>> folderQuery(String nodeName, String nodeTag, String diskType) {

        //业务元数据
        JSONObject metadata = new JSONObject();
        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);


        if (StringUtils.isNotEmpty(nodeName) && StringUtils.isNotEmpty(nodeTag)) {
            return BaseRespResult.errorResult("", "", "未找到查询条件");
        }
        try {
            List<DiskBO> diskBOList = diskNodeService.folderQuery(nodeName, nodeTag, diskType, metadata);
            //需要bo转vo给前端
            return BaseRespResult.successResult(transformVOList(diskBOList));
        } catch (DiskException e) {
            return BaseRespResult.errorResult("", "", e.getMessage());
        } catch (Exception e) {
            return BaseRespResult.errorResult("", "", "查询异常！");
        }
    }


    /**
     * 文件移动/复制
     *
     * @param opera        copy;move
     * @param nodeIds      被操作目录或文件ID集合，多个使用英文逗号分隔
     * @param targetNodeId 移动或复制到的新目录
     * @return 成功失败信息
     */
    @ResponseBody
    @RequestMapping(value = {"/opera/{opera}"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult copyAndMove(@PathVariable(name = "opera") String opera, String nodeIds, Long targetNodeId, String diskType) {

        //验证参数
        if (!StringUtils.isNotEmpty(nodeIds) || !StringUtil.isNotEmpty(diskType)) {
            return BaseRespResult.errorResult("", "", "参数错误！");
        }

        //业务元数据
        JSONObject metadata = new JSONObject();
        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);

        //归属人信息
        Owner owner = buildOwner(diskType);

        try {
            //权限验证
            if (DiskTypeEnum.COMPANY.getCode().equals(diskType)) {
                //获取当前登陆人信息
                EndUser currentUser = SecurityUserHolder.getCurrentUser();
                HashMap<String, String> userInfoMap = new HashMap<>();
                userInfoMap.put("roleId", currentUser.getRoleIds());
                userInfoMap.put("roleCode", currentUser.getRoleCodes());
                userInfoMap.put("company", currentUser.getJtgsId());
                userInfoMap.put("dept", currentUser.getDeptId());
                userInfoMap.put("userId", currentUser.getUserId());
                userInfoMap.put("userName", currentUser.getUsername());
                if (!diskNodeService.isDocAdmin(currentUser.getUserId()) && !currentUser.getSaasAdmin()) {
                    String nodeId = "null";
                    if (nodeIds != null) {
                        nodeId = nodeIds.toString();
                    }
                    diskNodeService.checkCompanyPower(userInfoMap, owner, nodeId, targetNodeId, opera);
                }
            }

            if ("copy".equals(opera)) {

                //进行复制操作
                List<DiskBO> returnBoList = diskNodeService.copyOperate(opera, nodeIds, targetNodeId, metadata, owner, diskType, false);

                //BO转VO
                List<DiskFileVO> returnVoList = new ArrayList<>();
                for (DiskBO diskBO : returnBoList) {
                    DiskFileVO diskFileVO = new DiskFileVO();
                    BeanUtils.copyProperties(diskBO, diskFileVO);
                    returnVoList.add(diskFileVO);
                }
                return BaseRespResult.successResult(returnVoList, "成功!");

            } else if ("move".equals(opera)) {
                diskNodeService.moveOperate(opera, nodeIds, targetNodeId, metadata, owner, diskType);
            }

            return BaseRespResult.successResult("", "成功!");
        } catch (DiskException e) {
            return BaseRespResult.errorResult("", "", e.getMessage());
        } catch (Exception e) {
            return BaseRespResult.errorResult("", "", "文件操作失败！");
        }
    }

    /**
     * 目录/文件重命名
     *
     * @param nodeId 目录/文件id
     * @param rename 新名称
     * @return DiskFileVO 目录/文件信息
     */
    @ResponseBody
    @RequestMapping(value = "/rename", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult rename(Long nodeId, String rename) {
        if (nodeId == null) {
            return BaseRespResult.errorResult("", "", "无文件标识！");
        } else if (!StringUtils.isNotEmpty(rename)) {
            return BaseRespResult.errorResult("", "", "文件命名不许为空！");
        }

        //业务元数据
        JSONObject metadata = new JSONObject();
        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);

        try {
            diskNodeService.rename(nodeId, rename, metadata);
            return BaseRespResult.successResult("重命名成功");
        } catch (DiskException e) {
            return BaseRespResult.errorResult("", "", e.getMessage());
        } catch (Exception e) {
            throw new DiskException("重命名失败！", DiskExceptionEnum.DISK_UPLOAD_ERROR, e);
        }
    }

    /**
     * 文件放入回收站
     *
     * @param nodeIds 目录/文件ID集合
     * @return 成功失败信息
     */
    @ResponseBody
    @RequestMapping(value = "/recycle", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult recycle(String nodeIds, String diskType) {

        if (!StringUtils.isNotEmpty(nodeIds)) {
            return BaseRespResult.errorResult("", "", "参数错误！");
        }
        //设置默认值
        if (!StringUtils.isNotEmpty(diskType)) {
            diskType = DiskTypeEnum.SELF.getCode();
        }

        //业务元数据
        JSONObject metadata = new JSONObject();
        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);

        try {

            //验证权限
            if (DiskTypeEnum.COMPANY.getCode().equals(diskType)) {
                //获取当前登陆人信息
                EndUser currentUser = SecurityUserHolder.getCurrentUser();
                HashMap<String, String> userInfoMap = new HashMap<>();
                userInfoMap.put("roleId", currentUser.getRoleIds());
                userInfoMap.put("roleCode", currentUser.getRoleCodes());
                userInfoMap.put("company", currentUser.getJtgsId());
                userInfoMap.put("dept", currentUser.getDeptId());
                userInfoMap.put("userId", currentUser.getUserId());
                userInfoMap.put("userName", currentUser.getUsername());
                //归属人信息
                Owner owner = buildOwner(diskType);
                if (!diskNodeService.isDocAdmin(currentUser.getUserId()) && !currentUser.getSaasAdmin()) {
                    diskNodeService.checkCompanyPower(userInfoMap, owner, nodeIds, null, OperationTypeEnum.UPLOAD.getCode());
                }
            }

            diskNodeService.recycle(nodeIds, diskType, metadata);
            return BaseRespResult.successResult("删除成功！");
        } catch (DiskException e) {
            return BaseRespResult.errorResult("", "", e.getMessage());
        } catch (Exception e) {
            return BaseRespResult.errorResult("", "", "删除异常！");
        }
    }


    /**
     * 编辑标签
     *
     * @param nodeIds  目录/文件ID集合
     * @param tags     标签颜色
     * @param diskType 网盘类型
     * @return 成功失败信息
     */
    @ResponseBody
    @RequestMapping(value = "/tag", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult tag(String nodeIds, String tags, String diskType) {
        if (!StringUtils.isNotEmpty(nodeIds)) {
            return BaseRespResult.errorResult("", "", "参数错误！");
        }

        //业务元数据
        JSONObject metadata = new JSONObject();
        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);

        try {
            diskNodeService.modifyTag(nodeIds, tags, diskType, metadata);
            return BaseRespResult.errorResult("", "", "更新成功");
        } catch (DiskException e) {
            return BaseRespResult.errorResult("", "", e.getMessage());
        } catch (Exception e) {
            return BaseRespResult.errorResult("", "", "修改异常！");
        }
    }

    /**
     * 传输列表记录查询
     *
     * @param key   搜索关键字
     * @param order 排序条件
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/transfer/list", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult<List<DiskTransferVO>> queryTransferList(String key, String order) {

        //业务元数据
        JSONObject metadata = new JSONObject();
        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);

        try {
            List<DiskBO> diskBOList = diskNodeService.queryTransferList(key, order, metadata);
            List<DiskTransferVO> diskTransferVOList = new ArrayList<>();
            //VO转BO
            for (DiskBO diskBO : diskBOList) {
                DiskTransferVO diskTransferVO = new DiskTransferVO();
                BeanUtils.copyProperties(diskBO, diskTransferVO);
                diskTransferVOList.add(diskTransferVO);
            }
            return BaseRespResult.successResult(diskTransferVOList);
        } catch (DiskException e) {
            return BaseRespResult.errorResult("", "", e.getMessage());
        } catch (Exception e) {
            return BaseRespResult.errorResult("", "", "查询异常！");
        }
    }


    /**
     * 删除传输记录接口
     *
     * @param transferIds
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/transfer/delete", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult deleteTransferList(String transferIds) {

        if (!StringUtils.isNotEmpty(transferIds)) {
            return BaseRespResult.errorResult("", "", "参数格式错误！");
        }

        //业务元数据
        JSONObject metadata = new JSONObject();
        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);

        try {
            //删除传输记录
            diskNodeService.deleteTransferList(transferIds, metadata);
            return BaseRespResult.successResult("", "删除成功！");
        } catch (DiskException e) {
            return BaseRespResult.errorResult("", "", e.getMessage());
        } catch (Exception e) {
            return BaseRespResult.errorResult("", "", "删除异常！");
        }
    }


    /**
     * 分享文件
     *
     * @param nodeIds 要分享的目录/文件ID
     * @param userIds 接收人ID
     * @return 成功失败信息
     */
    @ResponseBody
    @RequestMapping(value = "/share", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult share(String nodeIds, String userIds, String names) {

        //业务元数据
        JSONObject metadata = new JSONObject();
        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);

        //参数判断
        if (!StringUtils.isNotEmpty(nodeIds) || !StringUtils.isNotEmpty(userIds) || !StringUtils.isNotEmpty(names)) {
            return BaseRespResult.errorResult("", "", "参数异常！");
        }

        //分享文件添加
        try {
            diskNodeService.share(nodeIds, userIds, names, metadata);

            //分享人接收通知
            shareNotice(nodeIds, userIds, names);

            return BaseRespResult.successResult("分享成功");
        } catch (DiskException e) {
            return BaseRespResult.errorResult("", "", e.getMessage());
        } catch (Exception e) {
            return BaseRespResult.errorResult("", "", "分享异常！");
        }
    }


    /**
     * 分享通知
     *
     * @param nodeIds
     * @param userIds
     * @param names
     */
    public void shareNotice(String nodeIds, String userIds, String names) {
        String[] userIdsArray = userIds.split(",");
        EndUser endUser = SecurityUserHolder.getCurrentUser();
        //分享文件数
        int count = nodeIds.split(",").length;
        for (String userId : userIdsArray) {
            userMsgManaer.sendMsg(userId, "分享消息", endUser.getUsername()+"分享了网盘文件，请查看！", PushType.DISK, "", null);

            dwrManager.sendMsg(userId, "分享消息", "您有收到新的分享，请查看！");
        }
    }


    /**
     * 分享列表
     *
     * @param type  send发出的分享;receive接收的分享
     * @param key   搜索关键字
     * @param order 排序条件
     * @return
     */
    @ResponseBody
    @RequestMapping(value = {"/share/{type}/list"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult<List> shareList(@PathVariable(name = "type") String type, String key, String order) {

        //业务元数据
        JSONObject metadata = new JSONObject();
        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);
        String userId = metadata.getString(MetadataEnum.createUser.getCode());

        try {
            if (type.equals(ShareTypeEnum.RECEIVE.getCode())) {
                //清除此人被分享的未读数
                diskNodeService.cleanUnread(metadata);
                userMsgManaer.sendMsg(userId, "分享消息", "", PushType.DISK, "", null);
            }

            List<DiskBO> diskBOList = diskNodeService.shareListInfo(type, key, order, metadata);
            List<DiskShareVO> diskShareVOS = new ArrayList<>();
            for (DiskBO diskBO : diskBOList) {
                DiskShareVO diskShareVO = new DiskShareVO();
                BeanUtils.copyProperties(diskBO, diskShareVO);
                diskShareVOS.add(diskShareVO);
            }
            return BaseRespResult.successResult(diskShareVOS);
        } catch (DiskException e) {
            return BaseRespResult.errorResult("", "", e.getMessage());
        } catch (Exception e) {
            return BaseRespResult.errorResult("", "", "查询异常！");
        }
    }


    /**
     * 分享列表删除
     *
     * @param shareIds
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/share/delete", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult deleteShareList(String shareIds) {

        if (!StringUtils.isNotEmpty(shareIds)) {
            return BaseRespResult.errorResult("", "", "参数格式错误！");
        }

        //业务元数据
        JSONObject metadata = new JSONObject();
        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);

        try {
            //删除分享记录
            diskNodeService.deleteShareList(shareIds, metadata);
            return BaseRespResult.successResult("", "删除成功！");
        } catch (DiskException e) {
            return BaseRespResult.errorResult("", "", e.getMessage());
        } catch (Exception e) {
            return BaseRespResult.errorResult("", "", "删除异常！");
        }
    }


    /**
     * 分享转存
     *
     * @param shareIds     分享记录ID
     * @param targetNodeId 转存的新目录ID
     */
    @ResponseBody
    @RequestMapping(value = "/share/transfer", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult shareTransfer(String shareIds, Long targetNodeId, String diskType) {

        //验证参数
        if (!StringUtils.isNotEmpty(shareIds)) {
            return BaseRespResult.successResult("", "参数格式错误！");
        }

        //业务元数据
        JSONObject metadata = new JSONObject();
        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);

        //归属人信息
        Owner owner = buildOwner(diskType);

        //转存
        try {
            diskNodeService.shareTransfer(shareIds, targetNodeId, metadata, owner, diskType);
            return BaseRespResult.successResult("转存成功！");
        } catch (DiskException e) {
//            return BaseRespResult.errorResult("", "", e.getMessage());
//        } catch (Exception e) {
//            return BaseRespResult.errorResult("", "", "转存异常！");
//        }
            throw e;
        }
    }

    /**
     * 查询回收站接口
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/recycle/list", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult<List<DiskFileVO>> recycleList(String diskType, String key, String order) {

        //业务元数据
        JSONObject metadata = new JSONObject();
        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);

        try {
            List<DiskBO> diskBOList = diskNodeService.recycleList(diskType, key, metadata, order);
            List<DiskRecycleVO> diskRecycleVOS = new ArrayList<>();
            for (DiskBO diskBO : diskBOList) {
                DiskRecycleVO diskRecycleVO = new DiskRecycleVO();
                BeanUtils.copyProperties(diskBO, diskRecycleVO);
                diskRecycleVOS.add(diskRecycleVO);
            }
            return BaseRespResult.successResult(diskRecycleVOS);
        } catch (DiskException e) {
            return BaseRespResult.errorResult("", "", e.getMessage());
        } catch (Exception e) {
            return BaseRespResult.errorResult("", "", "查询异常！");
        }
    }

    /**
     * 清除回收站
     *
     * @param recycleIds 回收站记录ID,不传默认清空全部
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/recycle/clean", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult recycleClean(String recycleIds, String order) {
        if (!StringUtils.isNotEmpty(recycleIds)) {
            return BaseRespResult.errorResult("", "", "参数异常！");
        }

        //业务元数据
        JSONObject metadata = new JSONObject();
        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);

        try {
            diskNodeService.recycleClean(recycleIds, metadata);
            return BaseRespResult.successResult("删除成功！");
        } catch (DiskException e) {
            return BaseRespResult.errorResult("", "", e.getMessage());
        } catch (Exception e) {
            return BaseRespResult.errorResult("", "", "删除异常！");
        }
    }

    /**
     * 恢复回收站
     *
     * @param recycleIds 回收站记录ID
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/recycle/recovery", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult recycleRecovery(String recycleIds, String diskType) {

        //验证参数
        if (!StringUtils.isNotEmpty(recycleIds)) {
            return BaseRespResult.errorResult("", "", "参数格式异常！");
        }

        //归属人信息
        Owner owner = buildOwner(diskType);

        //业务元数据
        JSONObject metadata = new JSONObject();
        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);

        try {
            diskNodeService.recycleRecovery(recycleIds, metadata, owner);
            return BaseRespResult.successResult("", "恢复成功！");
        } catch (Exception e) {
            return BaseRespResult.errorResult("", "", "恢复失败！");
        }
    }


    /**
     * 微邮接口
     *
     * @param nodeIds
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/microMail", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult microMail(String nodeIds, String diskType) {

        if (!StringUtils.isNotEmpty(nodeIds) || !StringUtils.isNotEmpty(diskType)) {
            return BaseRespResult.errorResult("", "", "参数错误！");
        }

        //归属人信息
        Owner owner = buildOwner(diskType);
        //业务元数据
        JSONObject metadata = new JSONObject();
        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);

        try {
            //验证权限
            if (DiskTypeEnum.COMPANY.getCode().equals(diskType)) {
                //获取当前登陆人信息
                EndUser currentUser = SecurityUserHolder.getCurrentUser();
                HashMap<String, String> userInfoMap = new HashMap<>();
                userInfoMap.put("roleId", currentUser.getRoleIds());
                userInfoMap.put("roleCode", currentUser.getRoleCodes());
                userInfoMap.put("company", currentUser.getJtgsId());
                userInfoMap.put("dept", currentUser.getDeptId());
                userInfoMap.put("userId", currentUser.getUserId());
                userInfoMap.put("userName", currentUser.getUsername());
                if (!diskNodeService.isDocAdmin(currentUser.getUserId()) && !currentUser.getSaasAdmin()) {
                    diskNodeService.checkCompanyPower(userInfoMap, owner, nodeIds, null, OperationTypeEnum.MICROMAIL.getCode());
                }
            }

            ArrayList resultList = diskNodeService.microMail(nodeIds, diskType, metadata, owner);
            return BaseRespResult.successResult(resultList, "查询成功！");
        } catch (DiskException e) {
            return BaseRespResult.errorResult("", e.getErrorCode(), e.getMessage());
        } catch (Exception e) {
            return BaseRespResult.errorResult("", "", "查询异常！");
        }
    }


    /**
     * 检查未读状态
     *
     * @param diskType
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/tips/check", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult checkUnread(String diskType) {

        //业务元数据
        JSONObject metadata = new JSONObject();
        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);

        List<DiskBO> unreadList = null;
        try {
//            unreadList = diskNodeService.checkUnread(metadata);
            return BaseRespResult.successResult(unreadList.size(), "查询成功！");
        } catch (DiskException e) {
            return BaseRespResult.errorResult("", "", e.getMessage());
        }
    }


    /**
     * 操作记录查询
     *
     * @param nodeId 文件id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/log", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult findFileLog(String nodeId) {

        //验证参数
        if (!StringUtils.isNotEmpty(nodeId)) {
            return BaseRespResult.errorResult("", "", "参数异常!");
        }

//        List<DiskBO> longList = null;
        try {
            ArrayList longList = diskNodeService.checkLog(nodeId);
            return BaseRespResult.successResult(longList);
        } catch (DiskException e) {
//            return BaseRespResult.errorResult("", e.getErrorCode(), e.getMessage());
            throw e;
        } catch (Exception e) {
//            return BaseRespResult.errorResult("", "", "查询异常！");
            throw e;
        }
    }


    /**
     * 文件授权接口，设置权限
     *
     * @param nodeId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/empower", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult empower(String nodeId, String empowerPeople) {

        //参数验证
        if (!StringUtils.isNotEmpty(nodeId) || !StringUtils.isNotEmpty(empowerPeople)) {
            return BaseRespResult.errorResult("", "", "您未授权任何人员");
        }

        //业务元数据
        JSONObject metadata = new JSONObject();
        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);
        String nodeNam = nodeId;
        try {
            diskNodeService.empower(nodeId, nodeNam, empowerPeople, "", metadata);
            return BaseRespResult.successResult("", "设置成功!");
        } catch (DiskException e) {
            return BaseRespResult.errorResult("", e.getErrorCode(), e.getMessage());
        } catch (Exception e) {
            return BaseRespResult.errorResult("", "", "权限设置异常！");
        }
    }


    /**
     * 查询当前文件权限中人数
     *
     * @param nodeId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/powerNum", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult checkPowerInfo(String nodeId) {

        if (!StringUtils.isNotEmpty(nodeId)) {
            return BaseRespResult.errorResult("", "", "参数异常!");
        }

        //业务元数据
        JSONObject metadata = new JSONObject();
        //补充当前用户元数据
        MetadataUtil.setCreateMetadata(metadata);

        try {
            ArrayList list = diskNodeService.checkPowerInfo(nodeId, "", metadata);
            return BaseRespResult.successResult(list);
        } catch (DiskException e) {
            return BaseRespResult.errorResult("", e.getErrorCode(), e.getMessage());
        } catch (Exception e) {
            return BaseRespResult.errorResult("", "", "查修异常");
        }
    }


    /**
     * BO转VO
     *
     * @param fileBos BO集合
     * @return java.util.List<com.je.paas.document.vo.FileVO>
     */
    private List<DiskFileVO> transformVOList(List<DiskBO> fileBos) {
        //构建VO
        List<DiskFileVO> diskFileVOS = new ArrayList<>();
        for (DiskBO diskBO : fileBos) {
            diskFileVOS.add(transformVO(diskBO));
        }
        return diskFileVOS;
    }


    /**
     * BO转VO
     *
     * @param diskBO BO实体
     * @return java.util.List<com.je.paas.document.vo.FileVO>
     */
    private DiskFileVO transformVO(DiskBO diskBO) {

        DiskFileVO vo = new DiskFileVO();
        BeanUtils.copyProperties(diskBO, vo);
        return vo;
    }

    /**
     * 构建归属人信息
     *
     * @param diskType 网盘类型
     * @return com.je.paas.disk.model.bo.Owner
     */
    private Owner buildOwner(String diskType) {
        //网盘类型枚举
        DiskTypeEnum diskTypeEnum = DiskTypeEnum.getDefault(diskType);
        if (diskTypeEnum == null) {
            throw new DiskException("网盘类型错误", DiskExceptionEnum.DISK_UPLOAD_PARAM_ERROR);
        }
        //文件归属对象

        //归属人信息
        Owner owner = new Owner(SecurityUserHolder.getCurrentUser().getUserId(), SecurityUserHolder.getCurrentUser().getUsername());
        if (diskTypeEnum == DiskTypeEnum.COMPANY) {
            owner = new Owner(SecurityUserHolder.getCurrentUser().getZhId(), SecurityUserHolder.getCurrentUser().getZhMc());
        }
        if (StringUtils.isBlank(owner.getOwnerId())) {
            throw new DiskException(String.format("%s 查不到文件归属对象ID", diskType), DiskExceptionEnum.DISK_UPLOAD_PARAM_ERROR);
        }
        return owner;
    }


}